/**
 * Trigger video meta data update for a single video.
 * @param string Videoid of the YT video to update.
 */
function singleVideoMetaUpdate(videoid) {
  var country_listing = '<b data-title="Allowed in these countries">';
  $.ajax({
    type: 'get',
    url: '/update_video?videoid=' + videoid,
    data: {},
    dataType: 'json',
    success: function(message) {
      console.log(message);
      var countrys = JSON.parse(message['country_restriction']);
      if (!countrys) {
        country_listing += '<span class="label label-success">Updated: All Countries</span>';
      } else {
        var geo_type = "";
        if (message['country_restriction']['relationship'] == "allow"){
          geo_type = "success";
          country_listing += ' <span class="label label-' + geo_type + '">Updated:</span>';
        } else {
          geo_type = "important";
          country_listing += ' <span class="label label-' + geo_type + '">Updated:</span>';
        }
        
        var listOfGeos = countrys['$t'].split(" ");
        for (var i=0; i < listOfGeos.length; i++){
          country_listing += ' <span class="label label-' + geo_type + '">' + listOfGeos[i] +'</span>';
        }
        
      }
      country_listing += "</b>";
      $('#' + videoid + '_geos_list').html(country_listing);
      $('#' + videoid + '_view_counts').html(
          "<font color=\"green\">" + message['view_count'] + " views</font>");
    
      
    }
  });
}

function submitSearchForm(page){
  if (!page){
  var page = 1;
  }

  $.ajax({
    type: $('#search').attr("method"),
    url: $('#search').attr("action"),
    data: $('#search').serialize() + "&page_index=" + page,
    dataType: 'json',
    success: function(message) {
      $("#total_videos").html(message["total_videos"]);
      if (message["total_videos"] == 0 ) {
        $("#get_less_videos").addClass("disabled");
        $("#get_more_videos").addClass("disabled");
      } else if (message["total_videos"] > 199 ) {
        $("#get_less_videos").removeClass("disabled");
        $("#get_more_videos").removeClass("disabled");
      } else if (message["total_videos"] < 200 ){
        $("#get_less_videos").removeClass("disabled");
        $("#get_more_videos").addClass("disabled");
      }
      $("#video_content").html(message["content"]);
      $('#main').find('tr td:first-child img').lazyload()
    }
  });
 
  if (page == 1 || page == "1"){
    $("#get_less_videos").addClass("disabled");
  }
}

$( function() {
  // Close any popups if the mouse is clicked
  $('#close_block').click( function() {
    $('#main table form.modal-form, #notifications').hide()
    $('#close_block').hide()
  })

  $('#main').find('tr td:first-child img').lazyload()

  // Results ordering
  $('#order_by').find('ul a').click( function(e) {
    var defaultSortSelect = $('#order_by_field').html();
    e.preventDefault();
    $('#order_by_field').html($(this).html());
    $("#selected_sort_option").val($(this).attr('data-order'));
    if (defaultSortSelect != $(this).html()) {
      submitSearchForm();
    }
  });

  $("#searchButton").click(function (e) {
    e.preventDefault();
    submitSearchForm();
  });
  // Show the video preview modal
  $('#main').find('tr td:first-child a').live('click', function(e) {
    e.preventDefault()

    var vid = $(this).parent().parent().attr('data-id');

    singleVideoMetaUpdate(vid)

    $("#img" + vid).remove();
    var iframe_url = 'http://www.youtube.com/embed/'+ vid +'?autoplay=1&controls=0&enablejsapi=1'
    var iframe_html = '<iframe width="320" height="250" src="'+ iframe_url + '" frameborder="0" allowfullscreen></iframe>'
    $("#iframe"+vid).html(iframe_html);
 
  })

  $("#adv_form").click(function (e) {
    e.preventDefault();
    if ($("#adv_search").css('height') == "0px"){
      $("#adv_search").animate({height:'100%'}, 500);
      $(this).attr("src", "/static/img/arrow_up.png");

    } else {
      $("#adv_search").animate({height:'0px'}, 500);
      $(this).attr("src", "/static/img/arrow_down.png");
     
    }
  });


  $("#get_more_videos").click(function (e) {
    e.preventDefault();
    if (!$(this).hasClass("disabled")) {
      var page = parseInt($("#page_index").html()) + 1;
      $("#page_index").html(page)
      submitSearchForm(page);
   }
  });
 
  $("#get_less_videos").click(function (e) {
    e.preventDefault();
    if (!$(this).hasClass("disabled")) {
      var page = parseInt($("#page_index").html()) - 1;
      if (page == 0) {
        page = 1;
      }
      $("#page_index").html(page)
      submitSearchForm(page);
    }
  });

  // Tooltips for geo restrictions
  $('#main').find('table tr td:nth-child(2) p.geo b').tooltip();
  $('#adv_form').tooltip({"placement": "bottom"});

  // "Edit tags" links
  $('#main').find('table tr td a.edit').live('click', function(e) {
    e.preventDefault()
    var form_id = $(this).attr('data-form');
    var vid = $('#'+ form_id).attr("data-videoid");

    var tagid = $("#" + vid + "_tags");

    //loop through all previously saved tags and tick ones that match checkbox
    $(tagid).find("span").each(function( index ) {
      savedTagName = $(this).html();
      //console.log(' found saved tag = ' +index+ savedTagName)
      $('#'+ form_id + " input[type=checkbox]").each(function(i){
        if ($(this).val() == savedTagName) {
          //console.log('checkbox tagname '+ $(this).val());
          $(this).attr("checked", "checked");
        };
      })
    });
    $('#main table form..modal-form[id!='+ form_id +']').hide()
    $('#'+ form_id).toggle()
    $('#'+ form_id).find('input:first-child').focus()
    $('#close_block').show()
  })


  $(".tags").live('submit', function(e) {
    var form = $(this);
    var videoid =  form.attr('data-videoid');
    e.preventDefault();
    $('#main table form.modal-form, #notifications').hide()
    
    $.ajax({
      type: form.attr("method"),
      url: form.attr("action"),
      data: form.serialize(),
      dataType: 'json',
      success: function(message) {
        console.log(message);
        if (message["status"] == "SUCCESS") {
          var content = '';
          for (var i = 0; i < message['data'].length; i++) {
            content += ('<span class="label">' + message['data'][i] +'</span> ');
          }
          $('#' + videoid + '_tags').html(content);
        } else {
          $('#' + videoid + '_tags').html('<span class="label label-important">' + message["message"] + '</span>');
        }

      }
    });
  });

    
})
